package com.fanghaoran.notes.service.impl;

import com.alibaba.fastjson.JSON;
import com.fanghaoran.notes.bean.MyResult;
import com.fanghaoran.notes.bean.OrderDetail;
import com.fanghaoran.notes.dao.OrderDao;
import com.fanghaoran.notes.dao.UserDao;
import com.fanghaoran.notes.dao.impl.OrderDaoImpl;
import com.fanghaoran.notes.dao.impl.UserDaoImpl;
import com.fanghaoran.notes.entity.User;
import com.fanghaoran.notes.service.UserService;
import com.fanghaoran.notes.util.*;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;
import java.util.Properties;

/**
 * @Author: win11
 * @Date: 2023/04/14/15:09
 * @Description:
 */
public class UserServiceImpl implements UserService {
    /**
     * dao层对象
     */
    UserDao userDao=new UserDaoImpl();
    OrderDao orderDao=new OrderDaoImpl();

    @Override
    public MyResult login(User user) throws Exception {
        //拿到用户输入的密码,进行哈希加密运算
        byte[] encryptPassword = EncryptUtil.hashPassword(user.getPassword());
        //编码得到最终的加密后密码
        String hashPassword= Base64.getEncoder().encodeToString(encryptPassword);
        //将加密后的密码作为参数传入数据库进行比对,一致则说明密码正确
        user.setPassword(hashPassword);
        List<User> users = userDao.selectUserByNameAndPwd(user);
        if(users.isEmpty()){
            return new MyResult(Constants.EMPTY,null);
        }else{
            return new MyResult(Constants.NONEMPTY,users.get(0));
        }
    }

    @Override
    public MyResult register(User user) throws Exception {
        //对用户名和邮箱进行数据库查询,这两个都是唯一的
        List<User> users = userDao.selectUserByNameOrEmail(user);
        if(!users.isEmpty()){
            //用户/邮箱已存在
            return new MyResult(Constants.NONEMPTY,null);
        }else{
            //不存在 可以写入数据库
            //对密码进行加密
            byte[] encryptPassword = EncryptUtil.hashPassword(user.getPassword());
            //编码得到最终的加密后密码
            String hashPassword= Base64.getEncoder().encodeToString(encryptPassword);
            //将加密后的密码作为参数传入数据库
            user.setPassword(hashPassword);
            //盐
            user.setSalt(new String(Constants.SALT));
            //头像 未设置采用默认头像
            user.setHeadPhoto(Constants.DEFAULT_HEAD_PHOTO);
            //写入数据库
            Integer rows = userDao.insertUser(user);
            return StringUtil.returnOfUpdate(rows);
        }

    }

    @Override
    public MyResult getUserInfo(User user) throws Exception {
        List<User> users = userDao.selectUserByNameOrEmail(user);
        return StringUtil.returnOfSelect(users);
    }

    @Override
    public MyResult getUserInfoByUid(int uId) throws Exception {
        List<User> users = userDao.selectUserByUid(uId);
        return StringUtil.returnOfSelect(users);
    }


    @Override
    public MyResult sendCode(User user) throws Exception {
        //拿到邮箱,进行数据库校验(是否注册)
        List<User> users = userDao.selectUserByNameOrEmail(user);
        if(users.isEmpty()){
            //邮箱未注册
            return new MyResult(Constants.EMPTY,null);
        }else{
            //邮箱已注册,可以发送验证码
            //获取验证码
            String code=CodeUtil.getCode();
            //调用邮件工具类来发送邮件
            EmailUtil.sendEmail(user,code);

            //返回验证码
            return new MyResult(Constants.SUCCESS,code);
        }
    }



    @Override
    public MyResult modifyPwd(User user) throws SQLException {
        //对新密码进行加密
        byte[] encryptPassword = EncryptUtil.hashPassword(user.getPassword());
        //编码得到最终的加密后密码
        String hashPassword= Base64.getEncoder().encodeToString(encryptPassword);
        //将加密后的密码作为参数传入数据库
        user.setPassword(hashPassword);
        Integer rows = userDao.updatePwdByEmail(user);
        return StringUtil.returnOfUpdate(rows);
    }

    @Override
    public MyResult updatePhoto(int uId,String filename) throws SQLException {
        //调用数据库操作
        Integer rows = userDao.updateHeadPhoto(uId,filename);
        return StringUtil.returnOfUpdate(rows);
    }

    @Override
    public MyResult modifyBalance(int uId,String oId,BigDecimal totalCount) throws Exception {

        //根据用户id查询数据库数据并获取当前余额
        System.out.println("修改余额");
        List<User> users = userDao.selectUserByUid(uId);
        BigDecimal balance = users.get(0).getBalance();
        //如果当前余额不足
        if (balance.compareTo(totalCount) < 0) {
            return new MyResult(Constants.FAIL, "当前余额不足,请先充值");
        } else {
            //获取订单中各产品对应的信息及商家
            List<OrderDetail> orderDetails = orderDao.selectOrderDetail(oId);
            //支付后的余额
            BigDecimal remain = balance.subtract(totalCount);
            //修改订单状态
            orderDao.updateState(oId, Constants.ORDER_PAYED);
            //修改用户余额
            userDao.updateBalance(uId, remain);
            //修改商家余额
            for (OrderDetail orderDetail : orderDetails) {
                //卖家id
                int sellerId = orderDetail.getUId();
                //获取卖家余额
                List<User> sellers = userDao.selectUserByUid(sellerId);
                BigDecimal balanceOfSeller = sellers.get(0).getBalance();
                //卖家收钱后的余额
                BigDecimal remainOfSeller = balanceOfSeller.add(orderDetail.getCount());
                //修改商家余额
                userDao.updateBalance(sellerId, remainOfSeller);
            }
            return new MyResult(Constants.SUCCESS, null);
        }

        /*Connection connection = null;
        try {
            connection = JdbcUtil.getConnection();
            //开启事务
            connection.setAutoCommit(false);

            //根据用户id查询数据库数据并获取当前余额
            List<User> users = userDao.selectUserByUid(uId);
            BigDecimal balance = users.get(0).getBalance();
            //如果当前余额不足
            if (balance.compareTo(totalCount) < 0) {
                return new MyResult(Constants.FAIL, "当前余额不足,请先充值");
            } else {
                //获取订单中各产品对应的信息及商家
                List<OrderDetail> orderDetails = orderDao.selectOrderDetail(oId);
                //支付后的余额
                BigDecimal remain = balance.subtract(totalCount);
                //修改订单状态
                orderDao.updateState(oId, Constants.ORDER_PAYED);
                //修改用户余额
                userDao.updateBalance(uId, remain);
                //修改商家余额
                for (OrderDetail orderDetail : orderDetails) {
                    //卖家id
                    int sellerId = orderDetail.getUId();
                    //获取卖家余额
                    List<User> sellers = userDao.selectUserByUid(sellerId);
                    BigDecimal balanceOfSeller = sellers.get(0).getBalance();
                    //卖家收钱后的余额
                    BigDecimal remainOfSeller = balanceOfSeller.add(orderDetail.getCount());
                    //修改商家余额
                    userDao.updateBalance(sellerId, remainOfSeller);
                }
            }

            //提交事务
            connection.commit();
            return new MyResult(Constants.SUCCESS, null);
        } catch (SQLException e) {
            //回滚事务
            if (connection != null) {
                connection.rollback();
            }
            return new MyResult(Constants.FAIL, "数据库操作异常");
        } finally {
            //释放连接资源
            if (connection != null) {
                try {
                    JdbcUtil.freeConnection();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }*/
    }

    @Override
    public MyResult modifyBalanceOfRefund(int buyerId, int sellerId, BigDecimal totalCount) throws Exception {

        //执行事务
        // TODO: 业务逻辑在这里
        //获取退款金额以及退款者id
        //根据退款者id查询数据库数据并获取当前余额
        List<User> buyers = userDao.selectUserByUid(buyerId);
        BigDecimal buyerBalance = buyers.get(0).getBalance();
        //根据商家id查询数据库数据并获取当前余额
        List<User> sellers = userDao.selectUserByUid(sellerId);
        BigDecimal sellerBalance = sellers.get(0).getBalance();
        //如果当前余额不足
        if(sellerBalance.compareTo(totalCount) < 0){
            return new MyResult(Constants.FAIL,"当前余额不足,请先充值");
        }else{
            //商家退款后的金额
            BigDecimal sellerRemain = sellerBalance.subtract(totalCount);
            //买家退款后的金额
            BigDecimal buyerRemain = buyerBalance.add(totalCount);
            //修改商家金额
            userDao.updateBalance(sellerId,sellerRemain);
            System.out.println("退款这里");
            //修改买家金额
            userDao.updateBalance(buyerId,buyerRemain);
            return new MyResult(Constants.SUCCESS,null);
        }


        /*Connection connection=null;
        try {
            connection=JdbcUtil.getConnection();
            //开启事务
            connection.setAutoCommit(false);

            //执行事务
            // TODO: 业务逻辑在这里
            //获取退款金额以及退款者id
            //根据退款者id查询数据库数据并获取当前余额
            List<User> buyers = userDao.selectUserByUid(buyerId);
            BigDecimal buyerBalance = buyers.get(0).getBalance();
            //根据商家id查询数据库数据并获取当前余额
            List<User> sellers = userDao.selectUserByUid(buyerId);
            BigDecimal sellerBalance = sellers.get(0).getBalance();
            //如果当前余额不足
            if(sellerBalance.compareTo(totalCount) < 0){
                return new MyResult(Constants.FAIL,"当前余额不足,请先充值");
            }else{
                //商家退款后的金额
                BigDecimal sellerRemain = sellerBalance.subtract(totalCount);
                //买家退款后的金额
                BigDecimal buyerRemain = buyerBalance.add(totalCount);
                //修改商家金额
                userDao.updateBalance(sellerId,sellerRemain);
                System.out.println("退款这里");
                //修改买家金额
                userDao.updateBalance(buyerId,buyerRemain);
            }
            //提交事务
            connection.commit();
            return new MyResult(Constants.SUCCESS,null);
        } catch (SQLException e) {
            //回滚事务
            if (connection != null) {
                connection.rollback();
            }
            return new MyResult(Constants.FAIL, "发生错误");
        } catch (Exception e) {
            e.printStackTrace();
            return new MyResult(Constants.FAIL, "发生错误");
        } finally {
            //释放连接资源
            if (connection != null) {
                try {
                    JdbcUtil.freeConnection();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }*/
    }


}
